package game.players.states;

import java.util.Timer;

import com.uqbar.vainilla.DeltaState;
import com.uqbar.vainilla.colissions.CollisionDetector;

import utils.tasks.FinishSweepTask;
import game.ball.Possessed;
import game.ball.SoccerBall;
import game.players.SoccerPlayer;

public abstract class WithoutBallSweepingPlayer extends WithoutBall {
	
	private boolean isRight;
	private FinishSweepTask timerTask = new FinishSweepTask(this);

	public WithoutBallSweepingPlayer(SoccerPlayer player, boolean isRight) {
		super(player);
		this.crouchPlayer();
		
		this.setRight(isRight);
		if (this.isRight())
			this.setRightSprite();
		else
			this.setLeftSprite();
		
		Timer timer = new Timer();
		timer.schedule(this.getTimerTask() , 750);
	}
	
	private void crouchPlayer() {
		this.getPlayer().move(0, 20);
	}
	
	protected void getUpPlayer() {
		this.getPlayer().move(0, -20);
	}
	
	@Override
	public void update(DeltaState deltaState) {
		if (this.isRight())
			this.getPlayer().move(3, 0);
		else
			this.getPlayer().move(-3, 0);
		
		super.update(deltaState);

		SoccerBall ball = this.getPlayer().getScene().getSoccerBall();
		if (!ball.isFree() && this.collidesAgainstBall(ball, this.getPlayer())) {
			SoccerPlayer player = ((Possessed) ball.getState()).getPlayer();
			if (!player.isGoalKeeper())
				this.takePossessionBySnatch(ball, player);
		}
	}

	@Override
	public boolean collidesAgainstBall(SoccerBall ball, SoccerPlayer player) {
		return CollisionDetector.INSTANCE.collidesCircleAgainstRect(
				ball.getX(), ball.getY(), ball.getRatio(),
				player.getX(), player.getY(), player.getAppearance().getWidth(), player.getAppearance().getHeight()
				);
	}
	
	protected void takePossessionBySnatch(SoccerBall ball, SoccerPlayer player) {
		this.takeTheBall(ball);
		this.snatchTheBall();
		player.loseTheBall();
	}

	public abstract void finishSweep();
	
	protected abstract void takeTheBall(SoccerBall ball);
	
	public abstract void snatchTheBall();
	
	protected abstract void setRightSprite();
	
	protected abstract void setLeftSprite();
	
	
	
	
	
	public boolean isRight() {
		return isRight;
	}

	public void setRight(boolean isRight) {
		this.isRight = isRight;
	}

	public FinishSweepTask getTimerTask() {
		return timerTask;
	}

	public void setTimerTask(FinishSweepTask timerTask) {
		this.timerTask = timerTask;
	}

}
